from fastapi import APIRouter, Depends, HTTPException, Body, Query
from sqlalchemy.orm import Session
from ..database import get_db
from ..models.tag import Tag  # 导入Tag模型
from ..auth.jwt_handler import get_current_user
from ..models.user import User
import uuid
import json

router = APIRouter(
    prefix='/tags',  # 移除/api
    tags=['tags'],
)

# 修改为查询数据库中的Tag表获取用户的所有标签
@router.get('/')
def get_user_tags(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    try:
        # 查询当前用户创建的私有标签和所有公共标签（没有user_id的标签）
        user_tags = db.query(Tag).filter(
            (Tag.user_id == current_user.id) | (Tag.user_id == None)
        ).all()
        
        # 将SQLAlchemy模型转换为可序列化的字典列表
        return [
            {
                'id': str(tag.id),
                'name': tag.name,
                'user_id': str(tag.user_id) if tag.user_id else None,
                'created_at': tag.created_at.isoformat() if tag.created_at else None
            }
            for tag in user_tags
        ]
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f'获取标签失败: {str(e)}'
        )

# 创建新标签
@router.post('/')
def create_tag(
    tag_data: dict = Body(...),  # 使用字典接收整个请求体
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    try:
        # 调试信息：打印接收到的请求体
        print(f"Received tag_data: {tag_data}")
        print(f"Current user ID: {current_user.id}")
        print(f"Current user ID type: {type(current_user.id)}")
        
        # 确保我们能正确提取name字段
        name = None
        if isinstance(tag_data, dict):
            name = tag_data.get('name')
        elif isinstance(tag_data, str):
            try:
                parsed_data = json.loads(tag_data)
                if isinstance(parsed_data, dict):
                    name = parsed_data.get('name')
            except json.JSONDecodeError:
                pass
        
        print(f"Extracted name: {name}")
        
        # 检查标签名是否为空
        if not name or name.strip() == '':
            print("Tag name is empty")
            raise HTTPException(status_code=400, detail='标签名称不能为空')
        
        # 检查标签是否已存在
        print(f"Checking if tag '{name.strip()}' exists for user {current_user.id}")
        existing_tag = db.query(Tag).filter(
            Tag.name == name.strip(),
            Tag.user_id == current_user.id
        ).first()
        
        if existing_tag:
            print(f"Tag '{name.strip()}' already exists")
            raise HTTPException(status_code=400, detail='该标签已存在')
        
        # 创建新标签
        print(f"Creating new tag '{name.strip()}'")
        new_tag = Tag(
            name=name.strip(),  # 不需要手动设置id，数据库会自动生成
            user_id=current_user.id
        )
        
        db.add(new_tag)
        db.commit()
        db.refresh(new_tag)
        
        print(f"Tag created successfully: {new_tag.id}")
        return new_tag
    except HTTPException as e:
        print(f"HTTP Exception: {e.status_code} - {e.detail}")
        raise e
    except Exception as e:
        print(f"Error creating tag: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f'创建标签失败: {str(e)}'
        )

# 删除标签
@router.delete('/')
def delete_tag(
    id: str = Query(...),  # 使用查询参数获取标签ID
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    try:
        # 查找标签
        tag = db.query(Tag).filter(Tag.id == id).first()
        
        if not tag:
            raise HTTPException(status_code=404, detail='标签不存在')
        
        # 检查用户是否有权限删除标签
        if tag.user_id != current_user.id:
            raise HTTPException(status_code=403, detail='无权删除该标签')
        
        # 删除标签
        db.delete(tag)
        db.commit()
        
        return {'message': '标签已成功删除'}
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f'删除标签失败: {str(e)}'
        )

# 更新标签
@router.patch('/')
def update_tag(
    id: str = Query(...),  # 使用查询参数获取标签ID
    tag_data: dict = Body(...),  # 使用字典接收请求体
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    try:
        # 查找标签
        tag = db.query(Tag).filter(Tag.id == id).first()
        
        if not tag:
            raise HTTPException(status_code=404, detail='标签不存在')
        
        # 检查用户是否有权限更新标签
        if tag.user_id != current_user.id:
            raise HTTPException(status_code=403, detail='无权更新该标签')
        
        # 获取新的标签名称
        name = tag_data.get('name')
        
        if not name or name.strip() == '':
            raise HTTPException(status_code=400, detail='标签名称不能为空')
        
        # 检查更新后的标签名是否已存在
        existing_tag = db.query(Tag).filter(
            Tag.name == name.strip(),
            Tag.user_id == current_user.id,
            Tag.id != id  # 排除当前标签本身
        ).first()
        
        if existing_tag:
            raise HTTPException(status_code=400, detail='该标签名称已存在')
        
        # 更新标签名称
        tag.name = name.strip()
        db.commit()
        db.refresh(tag)
        
        # 返回更新后的标签信息
        return {
            'id': str(tag.id),
            'name': tag.name,
            'user_id': str(tag.user_id) if tag.user_id else None,
            'created_at': tag.created_at.isoformat() if tag.created_at else None
        }
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f'更新标签失败: {str(e)}'
        )